//
//  CustomTabBarViewController.m
//  CustomTabBarViewTest
//
//  Created by 赵莹 on 14-8-20.
//  Copyright (c) 2014年 赵莹. All rights reserved.
//

#import "CustomTabBarViewController.h"
#import "LeftViewVC.h"

#import "ButtonControlModelView.h"

@interface CustomTabBarViewController ()<UINavigationControllerDelegate>

@end
@implementation CustomTabBarViewController

#pragma mark 搜索执行
-(void)TheColumnSize:(NSString *)SearchText
{
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    if(_viewControllersArray.count<=_selectedIndex)
    {
        return;
    }
    if([[_viewControllersArray objectAtIndex:_selectedIndex] isKindOfClass:[ArticleViewModelVC class]])
    {
         //[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        
        ArticleViewModelVC *ArticleViewcontroll = [_viewControllersArray objectAtIndex:_selectedIndex];
        
        //第一次记录当前的Data,匹配个数
        //if(self.PastData.count<=ArticleViewcontroll.tablview.DataModel.count)
        //{
        //self.PastData = ArticleViewcontroll.tablview.DataModel;
        //}
        NSMutableArray *NewData = [[NSMutableArray alloc]init];
        
        for (YZCellMassgeModel  *model in  ArticleViewcontroll.tablview.DataModel)
        {
            
            //如果有则加入数组
            if ([model.Title rangeOfString:SearchText].location != NSNotFound)
            {
                [NewData addObject:model];
                
            }else if([model.Title rangeOfString:SearchText].location == NSNotFound)
            {
            
            }
        }
        

        [ArticleViewcontroll.tablview.DataModel removeAllObjects];
        [ArticleViewcontroll.tablview.DataModel addObjectsFromArray:NewData];
        [ArticleViewcontroll.tablview reloadData];
        ArticleViewcontroll.tablview.footer.hidden = YES;
        
        // [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
       
        
    }else if ([[_viewControllersArray objectAtIndex:_selectedIndex] isKindOfClass:[ParentViewModelVC class]])
    {
        // [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        
        ParentViewModelVC *ParentViewcontroll = [_viewControllersArray objectAtIndex:_selectedIndex];
        
        
        NSMutableArray *NewData = [[NSMutableArray alloc]init];
        
        
        for (id tableviewListID in ParentViewcontroll.Bgscrollview.subviews)
        {
            
           if([tableviewListID isKindOfClass:[ListTableviewModel class]])
           {
               ListTableviewModel  *tableviewList = tableviewListID;
           
                if(tableviewList.tag == ParentViewcontroll.Bgscrollview.contentOffset.x/Dev_ScreenWidth)
                {
                    
                    
                    for (YZCellMassgeModel  *model in  tableviewList.DataModel)
                    {
                        //如果有则加入数组
                        if ([model.Title rangeOfString:SearchText].location != NSNotFound)
                        {
                            [NewData addObject:model];
                            
                        }else if([model.Title rangeOfString:SearchText].location == NSNotFound)
                        {
                            
                        }
                    }
                            [tableviewList.DataModel removeAllObjects];
                            [tableviewList.DataModel addObjectsFromArray:NewData];
                            [tableviewList reloadData];
                    
                            tableviewList.footer.hidden = YES;
                   
                }
               
            }
            
         }
     
         //[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
     
    
    }else if ([[_viewControllersArray objectAtIndex:_selectedIndex] isKindOfClass:[ZineViewModelVC class]])
    {
    
    }


    
    [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
 
    
}




//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//
//    }
//    return self;
//}
-(void)DatachangviewButtonFontion
{

    for (UIButton *but in tabView.subviews )
    {
        [but removeFromSuperview];
    }
    [self createBottomButtons];

}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    tabView = [[UIView alloc] initWithFrame:CGRectMake(0, Dev_ScreenHeight-49, Dev_ScreenWidth, 49)];
    [self.view addSubview:tabView];
    tabView.backgroundColor = RGBCOLOR(252, 115, 148);
    
    tabBarImageView = [[UIImageView alloc] initWithFrame:tabView.bounds];
    [tabView addSubview:tabBarImageView];
    [self createBottomButtons];
    
    
}
#pragma mark 创建button
- (void)createBottomButtons{
    float buttonWidth = Dev_ScreenWidth/(_viewControllersArray.count);
    if (_bottomButtonArray == nil)
    {
        _bottomButtonArray = [[NSMutableArray alloc] init];
    }else
    {
        [_bottomButtonArray removeAllObjects];
    
    }
    
    
    for (int i = 0; i < _viewControllersArray.count; i ++)
    {
        ButtonControlModelView *bottomButton = [[ButtonControlModelView alloc]initWithButton:CGRectMake(buttonWidth * i, 0, buttonWidth, 49)];
        bottomButton.tag = i ;
        [bottomButton addTarget:self action:@selector(tabBarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        

        [tabView addSubview:bottomButton];
        [_bottomButtonArray addObject:bottomButton];
        
        
    }
}
- (void)tabBarButtonClicked:(id)sender
{
    ButtonControlModelView *clickedButton = (ButtonControlModelView *)sender;
    int index = (int)(clickedButton.tag);
    if (_selectedIndex == index)
    {
        return;
    }
    self.selectedIndex = index;
}
#pragma mark 设置viewControllersArray
- (void)setViewControllersArray:(NSArray *)viewControllersArray
{
    if (_viewControllersArray != viewControllersArray)
    {
        if(_viewControllersArray != nil)
        {
            UIViewController *previousViewController = [_viewControllersArray objectAtIndex:_selectedIndex];
            [previousViewController.view removeFromSuperview];
            //切换tabbar的时候已经把viewcontorller去掉了，所以记录上次的view的值应该是切换之后默认的0
            _selectedIndex = 0;
        }
        _viewControllersArray = viewControllersArray;
    }
}
#pragma mark 设置背景颜色
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    if (backgroundColor)
    {
        tabView.backgroundColor = backgroundColor;
    }
}
#pragma mark 设置背景图片
- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    if (backgroundImage)
    {
        tabBarImageView.image = backgroundImage;
    }
}

- (void)setNormalImageArray:(NSArray *)normalImageArray
{
    if(_normalImageArray != normalImageArray)
    {
        _normalImageArray = normalImageArray;
    }
    for (int i = 0; i < _bottomButtonArray.count; i ++)   ////此处_bottomButtonArray原为_normalImageArray。但数组溢出
    {
        ButtonControlModelView *button = [_bottomButtonArray objectAtIndex:i];
        [button.imageViews sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",[_normalImageArray objectAtIndex:i]]] placeholderImage:[UIImage imageNamed:@"bg"]];
          [button.imageViews sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",[_normalImageArray objectAtIndex:i]]]];
        
    }
}
- (void)setSelectedImageArray:(NSArray *)selectedImageArray
{
    if (_selectedImageArray != selectedImageArray)
    {
        _selectedImageArray = selectedImageArray;
    }
    for (int i = 0; i < _selectedImageArray.count; i ++)
    {
        
        
       // UIButton *button = [_bottomButtonArray objectAtIndex:i];
       // [button setImage:[UIImage imageNamed:[_selectedImageArray objectAtIndex:i]] forState:UIControlStateSelected];
        
//        NSString *strimageURL =[_selectedImageArray objectAtIndex:i];
//        UIImageView *imageviews = [[UIImageView alloc]init];
//        [imageviews sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",strimageURL]] placeholderImage:[UIImage imageNamed:@"bg"]];
//
//        UIImage *imagedata=[imageviews image];
//        
//        [button setImage:<#(UIImage *)#> forState:<#(UIControlState)#>]
//        [button setImage:imagedata] forState:UIControlStateSelected];
        
    }
}

- (void)setNormaltitleArray:(NSArray *)normaltitleArray
{
    if(_normaltitleArray != normaltitleArray)
    {
        _normaltitleArray = normaltitleArray;
    }
    for (int i = 0; i < _normaltitleArray.count; i ++)
    {
        
        ButtonControlModelView *button = [_bottomButtonArray objectAtIndex:i];
        button.imageViews.image =[UIImage imageNamed:[_normalImageArray objectAtIndex:i]];
     
        
    }
}

#pragma mark 设置默认控制器视图
- (void)setSelectedIndex:(int)selectedIndex
{
    //防止数组越界
    if(selectedIndex>=_viewControllersArray.count)
    {
        return;
    }
    //切换的时候把上次的view销毁，再替换新的view
    UIViewController *previousViewController = [_viewControllersArray objectAtIndex:_selectedIndex];
    [previousViewController.view removeFromSuperview];
    
   
    _selectedIndex = selectedIndex;
    UIViewController *currentViewController = [_viewControllersArray objectAtIndex:_selectedIndex];
    
    
    
    if ([currentViewController isKindOfClass:[UINavigationController class]])
    {
        ((UINavigationController *)currentViewController).delegate = self;
    }
    
    currentViewController.view.frame = CGRectMake(0, 0, Dev_ScreenWidth, Dev_ScreenHeight-49);
    [self.view addSubview:currentViewController.view];
    [self.view sendSubviewToBack:currentViewController.view];
    
//
//    if(_selectedIndex)
//    {
        ButtonControlModelView *currentButton = [_bottomButtonArray objectAtIndex:_selectedIndex];
        //currentButton.selected = NO;
        for (ButtonControlModelView *btn in _bottomButtonArray)
        {
             [btn setBackgroundColor:[UIColor clearColor]];
            
            if (btn == currentButton)
            {
                //btn.selected = NO;
                //btn.backgroundColor = [UIColor clearColor];  
                [currentButton setBackgroundColor:RGBACOLOR(0, 0, 0, 0.3)];
            }
        }
//    }
//    else
//    {
//        UIButton *currentButton = [_bottomButtonArray objectAtIndex:_selectedIndex-1];
//        currentButton.selected = YES;
//        // currentButton.backgroundColor = RGBCOLORS(@"#cc0001");
//        for (UIButton *btn in _bottomButtonArray)
//        {
//            if (btn != currentButton)
//            {
//                btn.selected = NO;
//                btn.backgroundColor = [UIColor clearColor];
//            }
//        }
//
//    }
}
- (void)showTabBar:(SlideDirection)direction animated:(BOOL)isAnimated
{

//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:0.28f];
//    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//
//    CGRect tabbarFrame = tabView.frame;
//    tabbarFrame.origin.x = 0;
//    tabView.frame = tabbarFrame;
//
//    [UIView commitAnimations];

	//根据压栈还是出栈设置TabBar初始位置
	CGRect tempRect = tabView.frame;
	tempRect.origin.x = self.view.bounds.size.width * ( (direction == SlideDirectionRight) ? -1 : 1);
	tabView.frame = tempRect;
    
	
    //执行动画
	[UIView animateWithDuration:isAnimated ? SLIDE_ANIMATION_DURATION : 0 delay:0 options:0 animations:^
	 {
		 //动画效果
		 CGRect tempRect = tabView.frame;
		 tempRect.origin.x = 0;
		 tabView.frame = tempRect;

		 
	 }
                     completion:^(BOOL finished)
	 {
         //动画结束时
         //重置当前视图控制器View的高度为整个屏幕的高度-TabBar的高度
		 UIViewController *currentViewController = [_viewControllersArray objectAtIndex:_selectedIndex];
		 
		 CGRect viewRect = currentViewController.view.frame;
		 viewRect.size.height = self.view.bounds.size.height - 49;
		 currentViewController.view.frame = viewRect;
	 }];
}

/*
 隐藏底部TabBar相关
 需要重置当前视图控制器View的高度为整个屏幕的高度
 */
- (void)hideTabBar:(SlideDirection)direction animated:(BOOL)isAnimated
{
    //获得当前视图控制器
	UIViewController *currentViewController = [_viewControllersArray objectAtIndex:_selectedIndex];
	//重置高度
	CGRect viewRect = currentViewController.view.frame;
	viewRect.size.height = self.view.bounds.size.height;
	currentViewController.view.frame = viewRect;
	
    //设置TabBar的位置
	CGRect tempRect = tabView.frame;
	tempRect.origin.x = 0;
	tabView.frame = tempRect;
	
    //采用Block的形式开启一个动画
	[UIView animateWithDuration:isAnimated ? SLIDE_ANIMATION_DURATION : 0 delay:0 options:0 animations:^(void)
     {
         //根据压栈还是出栈设置动画效果
		 CGRect tempRect = tabView.frame;
		 tempRect.origin.x = self.view.bounds.size.width * (direction == SlideDirectionLeft ? -1 : 1);
		 tabView.frame = tempRect;
		 
     }
                     completion:^(BOOL finished){}
     ];
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (!previousNavViewControllersArray)
	{
        //导航控制器中的视图数组
		previousNavViewControllersArray = navigationController.viewControllers;
	}
	
	
	BOOL isPush = NO;
	if ([previousNavViewControllersArray count] <= [navigationController.viewControllers count])
	{
		isPush = YES;
	}
	
    
	BOOL isPreviousHidden = [[previousNavViewControllersArray lastObject] hidesBottomBarWhenPushed];
	BOOL isCurrentHidden = viewController.hidesBottomBarWhenPushed;
    
    
	previousNavViewControllersArray = navigationController.viewControllers;
	
   	if (!isPreviousHidden && !isCurrentHidden)
	{
		return;
	}
	else if(isPreviousHidden && isCurrentHidden)
	{
		return;
	}
	else if(!isPreviousHidden && isCurrentHidden)
	{
		//隐藏tabbar 压栈
		[self hideTabBar:isPush ? SlideDirectionLeft : SlideDirectionRight  animated:animated];
        
	}
	else if(isPreviousHidden && !isCurrentHidden)
	{
		//显示tabbar 出栈
		[self showTabBar:isPush ? SlideDirectionLeft : SlideDirectionRight animated:animated];
	}
	
}



@end
